﻿namespace Hidistro.UI.SaleSystem.CodeBehind
{
    using Hidistro.Core;
    using Hidistro.Entities;
    using Hidistro.Entities.Orders;
    using Hidistro.Entities.Promotions;
    using Hidistro.Entities.Sales;
    using Hidistro.Membership.Context;
    using Hidistro.Membership.Core;
    using Hidistro.Messages;
    using Hidistro.SaleSystem.Catalog;
    using Hidistro.SaleSystem.Member;
    using Hidistro.SaleSystem.Shopping;
    using Hidistro.UI.Common.Controls;
    using Hidistro.UI.SaleSystem.Tags;
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using wnxd.javascript;
    using wnxd.Web;

    public class SubmmitOrder_new : HtmlTemplatedWebControl
    {
        private int buyAmount;
        private string productSku;
        private bool isBundling = false;
        private bool isCountDown = false;
        private bool isGroupBuy = false;
        private bool isSignBuy = false;
        private string buytype = "";
        private int bundlingid = 0;
        private ShoppingCartInfo shoppingCart;
        private IList<string> NotSelect;
        private Panel pannel_useraddress;
        private RegionSelector dropRegions;
        private HtmlTextArea txtAddress;
        private HtmlInputControl txtShipTo;
        private HtmlInputControl txtCellPhone;
        private Common_PaymentModeList paymentModeList;
        private wnxd_Shopping_LiList cartProductList;
        private HtmlGenericControl litProductAmount;
        private HtmlGenericControl lblTotalPrice;
        private HtmlGenericControl lblShippModePrice;
        private HtmlGenericControl hlkReducedPromotion;
        private HtmlGenericControl lblOrderTotal;
        private HtmlTextArea txtMessage;
        private HtmlInputHidden htmlCouponCode;
        private HtmlGenericControl litPoint;
        private HtmlSelect CmbCoupCode;
        private Label litTaxRate;
        protected override void AttachChildControls()
        {
            this.pannel_useraddress = (Panel)this.FindControl("pannel_useraddress");
            this.dropRegions = (RegionSelector)this.FindControl("dropRegions");
            this.txtAddress = (HtmlTextArea)this.FindControl("txtAddress");
            this.txtShipTo = (HtmlInputControl)this.FindControl("txtShipTo");
            this.txtCellPhone = (HtmlInputControl)this.FindControl("txtCellPhone");
            this.paymentModeList = (Common_PaymentModeList)this.FindControl("grd_Common_PaymentModeList");
            this.cartProductList = (wnxd_Shopping_LiList)this.FindControl("cartProductList");
            this.litProductAmount = (HtmlGenericControl)this.FindControl("litProductAmount");
            this.lblTotalPrice = (HtmlGenericControl)this.FindControl("lblTotalPrice");
            this.lblShippModePrice = (HtmlGenericControl)this.FindControl("lblShippModePrice");
            this.hlkReducedPromotion = (HtmlGenericControl)this.FindControl("hlkReducedPromotion");
            this.lblOrderTotal = (HtmlGenericControl)this.FindControl("lblOrderTotal");
            this.txtMessage = (HtmlTextArea)this.FindControl("txtMessage");
            this.htmlCouponCode = (HtmlInputHidden)this.FindControl("htmlCouponCode");
            this.litPoint = (HtmlGenericControl)this.FindControl("litPoint");
            this.CmbCoupCode = (HtmlSelect)this.FindControl("CmbCoupCode");
            this.litTaxRate = (Label)this.FindControl("litTaxRate");
            if (!this.Page.IsPostBack)
            {
                this.BindUserAddress();
                this.ReBindPayment();
                if (this.shoppingCart != null)
                {
                    SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);
                    this.litTaxRate.Text = masterSettings.TaxRate.ToString(CultureInfo.InvariantCulture);
                    this.BindShoppingCartInfo(this.shoppingCart);
                    this.pannel_useraddress.Visible = !HiContext.Current.User.IsAnonymous && (MemberProcessor.GetShippingAddressCount() > 0);
                    this.CmbCoupCode.DataTextField = "Name";
                    this.CmbCoupCode.DataValueField = "ClaimCode";
                    this.CmbCoupCode.DataSource = ShoppingProcessor.GetCoupon(this.shoppingCart.GetTotal());
                    this.CmbCoupCode.DataBind();
                    ListItem item = new ListItem("", "0");
                    this.CmbCoupCode.Items.Insert(0, item);
                }
            }
        }
        private void BindUserAddress()
        {
            if (!HiContext.Current.User.IsAnonymous)
            {
                Member user = HiContext.Current.User as Member;
                this.txtShipTo.Value = user.RealName;
                this.dropRegions.SetSelectedRegionId(new int?(user.RegionId));
                this.dropRegions.DataBind();
                this.txtAddress.Value = user.Address;
                this.txtCellPhone.Value = user.CellPhone;
            }
        }
        private void ReBindPayment()
        {
            IList<PaymentModeInfo> paymentModes = ShoppingProcessor.GetPaymentModes(PayApplicationType.payOnPC);
            IList<PaymentModeInfo> list2 = new List<PaymentModeInfo>();
            HttpCookie cookie = HiContext.Current.Context.Request.Cookies["Token_" + HiContext.Current.User.UserId.ToString()];
            if ((cookie != null) && !string.IsNullOrEmpty(cookie.Value))
            {
                foreach (PaymentModeInfo info in paymentModes)
                {
                    if ((((string.Compare(info.Gateway, "hishop.plugins.payment.alipay_shortcut.shortcutrequest", true) == 0) || (string.Compare(info.Gateway, "hishop.plugins.payment.alipaydirect.directrequest", true) == 0)) || ((string.Compare(info.Gateway, "hishop.plugins.payment.alipayassure.assurerequest", true) == 0) || (string.Compare(info.Gateway, "hishop.plugins.payment.alipay.standardrequest", true) == 0))) || ((string.Compare(info.Gateway, "hishop.plugins.payment.advancerequest", true) == 0) && !HiContext.Current.User.IsAnonymous))
                    {
                        list2.Add(info);
                    }
                }
            }
            else
            {
                foreach (PaymentModeInfo info in paymentModes)
                {
                    if (string.Compare(info.Gateway, "hishop.plugins.payment.alipay_shortcut.shortcutrequest", true) != 0)
                    {
                        list2.Add(info);
                    }
                    if ((string.Compare(info.Gateway, "hishop.plugins.payment.advancerequest", true) == 0) && HiContext.Current.User.IsAnonymous)
                    {
                        list2.Remove(info);
                    }
                }
            }
            this.paymentModeList.DataSource = list2;
            this.paymentModeList.DataBind();
        }
        private void BindShoppingCartInfo(ShoppingCartInfo shoppingCart)
        {
            if (shoppingCart.LineItems.Count > 0)
            {
                IList<ShoppingCartItemInfo> lineitems = new List<ShoppingCartItemInfo>();
                for (int i = 0; i < shoppingCart.LineItems.Count; i++)
                {

                    if (shoppingCart.LineItems[i].IsSelect) lineitems.Add(shoppingCart.LineItems[i]);
                }
                this.cartProductList.DataSource = lineitems;
                this.cartProductList.DataBind();
            }
            this.litProductAmount.InnerText = shoppingCart.GetAmount().ToString("F0");
            this.lblTotalPrice.InnerText = shoppingCart.GetAmount().ToString("F0");
            if (shoppingCart.IsReduced)
            {
                this.hlkReducedPromotion.InnerText = shoppingCart.ReducedPromotionAmount.ToString("F0");
            }
            this.lblOrderTotal.InnerText = shoppingCart.GetTotal().ToString("F0");
            this.litPoint.InnerText = shoppingCart.GetPoint().ToString();
        }
        protected override void OnInit(EventArgs e)
        {
            if (((int.TryParse(this.Page.Request.QueryString["buyAmount"], out this.buyAmount) && !string.IsNullOrEmpty(this.Page.Request.QueryString["productSku"])) && !string.IsNullOrEmpty(this.Page.Request.QueryString["from"])) && (this.Page.Request.QueryString["from"] == "groupBuy"))
            {
                this.productSku = this.Page.Request.QueryString["productSku"];
                this.isGroupBuy = true;
                this.shoppingCart = ShoppingCartProcessor.GetGroupBuyShoppingCart(this.productSku, this.buyAmount);
                this.buytype = "GroupBuy";
            }
            else if (((int.TryParse(this.Page.Request.QueryString["buyAmount"], out this.buyAmount) && !string.IsNullOrEmpty(this.Page.Request.QueryString["productSku"])) && !string.IsNullOrEmpty(this.Page.Request.QueryString["from"])) && (this.Page.Request.QueryString["from"] == "countDown"))
            {
                this.productSku = this.Page.Request.QueryString["productSku"];
                this.isCountDown = true;
                this.shoppingCart = ShoppingCartProcessor.GetCountDownShoppingCart(this.productSku, this.buyAmount);
                this.buytype = "CountDown";
            }
            else if (((int.TryParse(this.Page.Request.QueryString["buyAmount"], out this.buyAmount) && !string.IsNullOrEmpty(this.Page.Request.QueryString["productSku"])) && !string.IsNullOrEmpty(this.Page.Request.QueryString["from"])) && (this.Page.Request.QueryString["from"] == "signBuy"))
            {
                this.productSku = this.Page.Request.QueryString["productSku"];
                this.isSignBuy = true;
                this.shoppingCart = ShoppingCartProcessor.GetShoppingCart(this.productSku, this.buyAmount, true);
            }
            else if (((int.TryParse(this.Page.Request.QueryString["buyAmount"], out this.buyAmount) && !string.IsNullOrEmpty(this.Page.Request.QueryString["Bundlingid"])) && !string.IsNullOrEmpty(this.Page.Request.QueryString["from"])) && (this.Page.Request.QueryString["from"] == "Bundling"))
            {
                this.productSku = this.Page.Request.QueryString["Bundlingid"];
                if (int.TryParse(this.productSku, out this.bundlingid))
                {
                    this.shoppingCart = ShoppingCartProcessor.GetShoppingCart(this.bundlingid, this.buyAmount);
                    this.isBundling = true;
                    this.buytype = "Bundling";
                }
            }
            else
            {
                dynamic t = new json(Page.Request["NotBuy"]);
                this.NotSelect = t;
                this.shoppingCart = ShoppingCartProcessor.GetShoppingCart(this.NotSelect);
                if ((this.shoppingCart != null) && (this.shoppingCart.GetQuantity() == 0))
                {
                    this.buytype = "0";
                }
            }
            if (this.shoppingCart == null)
            {
                this.Page.Response.Redirect(Globals.ApplicationPath + "/ResourceNotFound.aspx?errorMsg=" + Globals.UrlEncode("该件商品已经被管理员删除"));
            }
            else
            {
                if (this.SkinName == null)
                {
                    this.SkinName = "Skin-SubmmitOrder_new.html";
                }
                base.OnInit(e);
            }
        }
        protected void CreateOrder()
        {
            if (this.ValidateCreateOrder())
            {
                Web web = Web.FindFirst();
                OrderInfo orderInfo = this.GetOrderInfo(this.shoppingCart);
                if (this.shoppingCart.GetQuantity() > 1)
                {
                    this.isSignBuy = false;
                }
                if (orderInfo == null)
                {
                    web.AddScript("alert('购物车中已经没有任何商品');");
                }
                else if (orderInfo.GetTotal() < 0M)
                {
                    web.AddScript("alert('订单金额不能为负');");
                }
                else
                {
                    if (!HiContext.Current.User.IsAnonymous)
                    {
                        int totalNeedPoint = this.shoppingCart.GetTotalNeedPoint();
                        int points = ((Member)HiContext.Current.User).Points;
                        if ((points >= 0) && (totalNeedPoint > points))
                        {
                            web.AddScript("alert('您当前的积分不够兑换所需积分');");
                            return;
                        }
                    }
                    if (this.isCountDown)
                    {
                        CountDownInfo countDownInfo = ProductBrowser.GetCountDownInfo(this.shoppingCart.LineItems[0].ProductId);
                        if (countDownInfo.EndDate < DateTime.Now)
                        {
                            web.AddScript("alert('此订单为抢购订单，但抢购时间已到！');");
                            return;
                        }
                        if (this.shoppingCart.LineItems[0].Quantity > countDownInfo.MaxCount)
                        {
                            web.AddScript("alert('" + "你购买的数量超过限购数量:" + countDownInfo.MaxCount.ToString() + "');");
                            return;
                        }
                        int num3 = ShoppingProcessor.CountDownOrderCount(this.shoppingCart.LineItems[0].ProductId);
                        if ((num3 + this.shoppingCart.LineItems[0].Quantity) > countDownInfo.MaxCount)
                        {
                            web.AddScript("alert('" + string.Format("你已经抢购过该商品{0}件，每个用户只允许抢购{1}件,如果你有未付款的抢购单，请及时支付！", num3, countDownInfo.MaxCount) + "');");
                            return;
                        }
                    }
                    try
                    {
                        if (ShoppingProcessor.CreatOrder(orderInfo))
                        {
                            Messenger.OrderCreated(orderInfo, HiContext.Current.User);
                            orderInfo.OnCreated();
                            if (this.shoppingCart.GetTotalNeedPoint() > 0)
                            {
                                ShoppingProcessor.CutNeedPoint(this.shoppingCart.GetTotalNeedPoint(), orderInfo.OrderId);
                            }
                            if (!(((this.isCountDown || this.isGroupBuy) || this.isSignBuy) || this.isBundling))
                            {
                                ShoppingCartProcessor.ClearShoppingCart();
                            }
                            if (!(HiContext.Current.User.IsAnonymous || (MemberProcessor.GetShippingAddressCount() != 0)))
                            {
                                string ShipTo = this.Page.Request.Form["SubmmitOrder$txtShipTo"];
                                string Address = this.Page.Request.Form["SubmmitOrder$txtAddress"];
                                string CellPhone = this.Page.Request.Form["SubmmitOrder$txtCellPhone    "];
                                int region = int.Parse(this.Page.Request.Form["regionSelectorValue"]);
                                ShippingAddressInfo shippingAddress = new ShippingAddressInfo
                                {
                                    UserId = HiContext.Current.User.UserId,
                                    ShipTo = Globals.HtmlEncode(ShipTo.Trim()),
                                    RegionId = region,
                                    Address = Globals.HtmlEncode(Address.Trim()),
                                    CellPhone = CellPhone.Trim()
                                };
                                MemberProcessor.AddShippingAddress(shippingAddress);
                            }
                            this.Page.Response.Redirect(Globals.GetSiteUrls().UrlData.FormatUrl("FinishOrder", new object[] { orderInfo.OrderId }));
                        }
                    }
                    catch (Exception exception)
                    {
                        web.AddScript("alert('" + exception.ToString() + "');");
                    }
                }
            }
        }
        private bool ValidateCreateOrder()
        {
            Web web = Web.FindFirst();
            int region;
            if (!int.TryParse(this.Page.Request.Form["regionSelectorValue"], out region) || region == 0)
            {
                web.AddScript("alert('请选择收货地址');");
                return false;
            }
            string pattern = @"[\u4e00-\u9fa5a-zA-Z]+[\u4e00-\u9fa5_a-zA-Z0-9]*";
            Regex regex = new Regex(pattern);
            string ShipTo = this.Page.Request.Form["SubmmitOrder$txtShipTo"];
            if (!(!string.IsNullOrEmpty(ShipTo) && regex.IsMatch(ShipTo.Trim())))
            {
                web.AddScript("alert('请输入正确的收货人姓名');");
                return false;
            }
            ShipTo = ShipTo.Trim();
            if ((ShipTo.Length < 2) || (ShipTo.Length > 20))
            {
                web.AddScript("alert('收货人姓名长度应在2-20个字符之间');");
                return false;
            }
            string Address = this.Page.Request.Form["SubmmitOrder$txtAddress"];
            if (string.IsNullOrEmpty(Address))
            {
                web.AddScript("alert('请输入收货人详细地址');");
                return false;
            }
            string CellPhone = this.Page.Request.Form["SubmmitOrder$txtCellPhone"];
            if (string.IsNullOrEmpty(CellPhone))
            {
                web.AddScript("alert('电话号码和手机号码必填其一');");
                return false;
            }
            var a = @"^((\(\d{3}\))|(\d{3}\-))?13\d{9}|14[57]\d{8}|15\d{9}|18\d{9}$";
            Regex regexs = new Regex(a);
            if (CellPhone.ToString().Length != 11 || !regexs.IsMatch(CellPhone.Trim()))
            {
                web.AddScript("alert('请输入正确的手机号码');");
                return false;
            }
            string PaymentModeId = this.Page.Request.Form["SubmmitOrder$inputPaymentModeId"];
            if (string.IsNullOrEmpty(PaymentModeId))
            {
                web.AddScript("alert('请选择支付方式');");
                return false;
            }

            return true;
        }
        private OrderInfo GetOrderInfo(ShoppingCartInfo shoppingCartInfo)
        {
            BundlingInfo bundlingInfo;
            OrderInfo orderInfo = ShoppingProcessor.ConvertShoppingCartToOrder(shoppingCartInfo, this.isGroupBuy, this.isCountDown, this.isSignBuy);
            if (orderInfo == null)
            {
                return null;
            }
            if (this.Page.Request.Form["SubmmitOrder$chkTax"] != null)
            {
                SiteSettings masterSettings = SettingsManager.GetMasterSettings(false);
                orderInfo.Tax = (orderInfo.GetTotal() * masterSettings.TaxRate) / 100M;
                if (this.isBundling)
                {
                    bundlingInfo = ProductBrowser.GetBundlingInfo(this.bundlingid);
                    orderInfo.Tax = (bundlingInfo.Price * masterSettings.TaxRate) / 100M;
                }
                orderInfo.InvoiceTitle = this.Page.Request.Form["txtInvoiceTitle"];
            }
            if (this.isGroupBuy)
            {
                GroupBuyInfo productGroupBuyInfo = ProductBrowser.GetProductGroupBuyInfo(shoppingCartInfo.LineItems[0].ProductId);
                orderInfo.GroupBuyId = productGroupBuyInfo.GroupBuyId;
                orderInfo.NeedPrice = productGroupBuyInfo.NeedPrice;
            }
            if (this.isCountDown)
            {
                CountDownInfo countDownInfo = ProductBrowser.GetCountDownInfo(this.shoppingCart.LineItems[0].ProductId);
                orderInfo.CountDownBuyId = countDownInfo.CountDownId;
            }
            if (this.isBundling)
            {
                bundlingInfo = ProductBrowser.GetBundlingInfo(this.bundlingid);
                orderInfo.BundlingID = bundlingInfo.BundlingID;
                orderInfo.BundlingPrice = bundlingInfo.Price;
                orderInfo.Points = this.shoppingCart.GetPoint(bundlingInfo.Price);
            }
            orderInfo.OrderId = this.GenerateOrderId();
            orderInfo.OrderDate = DateTime.Now;
            IUser user = HiContext.Current.User;
            orderInfo.UserId = user.UserId;
            orderInfo.Username = user.Username;
            if (!user.IsAnonymous)
            {
                Member member = user as Member;
                orderInfo.EmailAddress = member.Email;
                orderInfo.RealName = member.RealName;
                orderInfo.QQ = member.QQ;
                orderInfo.Wangwang = member.Wangwang;
                orderInfo.MSN = member.MSN;
            }
            orderInfo.Remark = Globals.HtmlEncode(this.Page.Request.Form["SubmmitOrder$txtMessage"]);
            orderInfo.OrderStatus = OrderStatus.WaitBuyerPay;
            orderInfo.RefundStatus = RefundStatus.None;
            this.FillOrderCoupon(orderInfo);
            this.FillOrderShippingMode(orderInfo, shoppingCartInfo);
            this.FillOrderPaymentMode(orderInfo);
            orderInfo.OrderSource = OrderSource.PC;
            return orderInfo;
        }
        private string GenerateOrderId()
        {
            string str = string.Empty;
            Random random = new Random();
            for (int i = 0; i < 7; i++)
            {
                int num = random.Next();
                str = str + ((char)(0x30 + ((ushort)(num % 10)))).ToString();
            }
            int v = random.Next(0, 9);
            return (DateTime.Now.ToString("yyyyMMdd") + str + v);
        }
        private void FillOrderCoupon(OrderInfo orderInfo)
        {
            string CouponCode = this.Page.Request.Form["SubmmitOrder$htmlCouponCode"];
            if (!string.IsNullOrEmpty(CouponCode))
            {
                CouponInfo info = ShoppingProcessor.UseCoupon(this.shoppingCart.GetTotal(), CouponCode);
                if (info != null)
                {
                    orderInfo.CouponName = info.Name;
                    if (info.Amount.HasValue)
                    {
                        orderInfo.CouponAmount = info.Amount.Value;
                    }
                    orderInfo.CouponCode = this.htmlCouponCode.Value;
                    orderInfo.CouponValue = info.DiscountValue;
                }
            }
        }
        private void FillOrderPaymentMode(OrderInfo orderInfo)
        {
            string PaymentModeId = this.Page.Request.Form["SubmmitOrder$inputPaymentModeId"];
            orderInfo.PaymentTypeId = int.Parse(PaymentModeId);
            PaymentModeInfo paymentMode = ShoppingProcessor.GetPaymentMode(orderInfo.PaymentTypeId);
            if (paymentMode != null)
            {
                orderInfo.PaymentType = Globals.HtmlEncode(paymentMode.Name);
                orderInfo.PayCharge = ShoppingProcessor.CalcPayCharge(orderInfo.GetTotal(), paymentMode);
                orderInfo.Gateway = paymentMode.Gateway;
            }
        }
        private void FillOrderShippingMode(OrderInfo orderInfo, ShoppingCartInfo shoppingCartInfo)
        {
            int region;
            if (int.TryParse(this.Page.Request.Form["regionSelectorValue"], out region))
            {
                orderInfo.RegionId = region;
                orderInfo.ShippingRegion = RegionHelper.GetFullRegion(region, "，");
            }
            string Address = this.Page.Request.Form["SubmmitOrder$txtAddress"];
            orderInfo.Address = Globals.HtmlEncode(Address.Trim());
            string ShipTo = this.Page.Request.Form["SubmmitOrder$txtShipTo"];
            orderInfo.ShipTo = Globals.HtmlEncode(ShipTo.Trim());
            string CellPhone = this.Page.Request.Form["SubmmitOrder$txtCellPhone"];
            orderInfo.CellPhone = CellPhone.Trim();
            orderInfo.ShippingModeId = 2;
            orderInfo.ShipToDate = this.Page.Request.Form["ShipToDate"];
            ShippingModeInfo shippingMode = ShoppingProcessor.GetShippingMode(orderInfo.ShippingModeId, true);
            if (shippingMode != null)
            {
                orderInfo.ShippingModeId = shippingMode.ModeId;
                orderInfo.ModeName = shippingMode.Name;
                if (!(shoppingCartInfo.IsFreightFree || ((shoppingCartInfo.LineItems.Count<ShoppingCartItemInfo>(a => !a.IsfreeShipping) <= 0) && (shoppingCartInfo.LineGifts.Count <= 0))))
                {
                    orderInfo.AdjustedFreight = orderInfo.Freight = ShoppingProcessor.CalcFreight(orderInfo.RegionId, shoppingCartInfo.Weight, shippingMode);
                }
                else
                {
                    orderInfo.AdjustedFreight = orderInfo.Freight = 0M;
                }
            }
        }
    }
}

